import { defineStore } from 'pinia'
import { ref } from 'vue';
import { useEmojiStore } from './emojiStore';

export const useCategoryStore = defineStore(
    'category',
    // 组合式逻辑（第一个函数参数）
    () => {
        const categoryList = ref([])

        function initAllCat() {
            const emojiStore = useEmojiStore()
            categoryList.value[0] = {
                id: -1,
                name: '全部表情',
                emojiList: emojiStore.emojiList
            }
        }

        function newCategory(name) {
            const newId = categoryList.value.length === 0
                ? 0
                : Math.max(...categoryList.value.map(e => e.id)) + 1;

            const newCat = {
                id: newId,
                name: name,
                emojiList: []
            }

            categoryList.value.push(newCat)
            console.log('新增后的分类', categoryList.value)
        }

        async function readCatList() {
            console.log(categoryList.value)
            return categoryList.value
        }

        function importImageInCat(id, emojiId) {
            let newCat = categoryList.value
            newCat.forEach((item, index) => {
                if (item.id === id) {
                    item.emojiList.push(emojiId)
                }
            })
            categoryList.value = newCat
        }

        return { categoryList, newCategory, readCatList, importImageInCat, initAllCat }
    },
    // 持久化配置（第三个参数）
    {
        persist: {
            key: 'pinia-category', // 自定义 localStorage 的 key
            paths: ['categoryList'] // 需要持久化的字段
        }
    }
)